/*
	$Id: linkopener.js,v 1.22 2014-01-16 19:38:38 martin Exp $
	Open the links and display the results
	Author: Eike, Team Spockholm
	Todo:
	- all
*/


javascript:(function (){
	var rev=/,v \d+\.(\d+)\s201/.exec("$Id: linkopener.js,v 1.22 2014-01-16 19:38:38 martin Exp $")[1],
	version='Linkopener v0.'+rev;
	var spocklet='linkopen';
	var alternative = false;
	if (unix_timestamp() >= 1369152000 && unix_timestamp <= 1369170000){
		alternative = true;
	}
	var debug = false;
	var logs=[];
	var docid;
	var access_token =FB.getAuthResponse().accessToken; 

	try {
		if (localStorage.getItem) {
			storage = localStorage;
		}
		else if (window.localStorage.getItem) {
			storage = window.localStorage;
		}
	}
	catch(storagefail) {}

	if (navigator.appName == 'Microsoft Internet Explorer') {
		alert('You are using Internet Explorer, this bookmarklet will not work.\nUse Firefox or Chrome instead.');
		return;
	}

	//hack to kill the resizer calls
	iframeResizePipe = function() {};
		
	var http = 'http://';
	if (/https/.test(document.location)) {
		http = 'https://';
	}
	var preurl = http+'facebook-ca2.mafiawars.zynga.com/mwfb/remote/html_server.php?';
	
	//setup the initial html
	var style = '<style type="text/css">'+
		'.messages {border: 1px solid #888888; margin-bottom: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-border-radius: 5px;}'+
		'.messages img{margin:0 3px;vertical-align:middle}'+
		'.messages input {border: 1px solid #888888; -moz-border-radius: 3px; border-radius: 3px; -webkit-border-radius: 2px;padding 0;background: #000; color: #FFF; width: 32px;}'+
		'#'+spocklet+'_post { display:none; }'+
		
	'</style>';

	var logo = '<a href="http://www.spockholm.com/mafia/testing.php?'+spocklet+'" target="_blank"><img src="http://static.spocklet.com/banner-spockholm-mafia-tools.png" alt="Spockholm Mafia Tools" title="Spockholm Mafia Tools" width="425" height="60" style="margin-bottom: 10px;" /></a>';

	var spocklet_html =
	'<div id="'+spocklet+'_main">'+
		style+
		'<table class="messages">'+
		'<tr><td colspan="3" align="center" style="text-align:center;">'+logo+'<br />'+
			'<a href="http://www.spockholm.com/mafia/donate.php#'+spocklet+'" id="'+spocklet+'_donate" class="sexy_button_new short white" target="_blank" title="Like what we do? Donate to Team Spockholm" alt="Like what we do? Donate to Team Spockholm"><span><span>Donate</span></span></a>'+
//			'&nbsp;<a href="http://www.spockholm.com/mafia/help.php#" id="'+spocklet+'_help" class="sexy_button_new short" target="_blank" title="Get help" alt="Get help"><span><span>Help</span></span></a>'+
			'&nbsp;<a href="#" id="'+spocklet+'_stop" class="sexy_button_new short orange" title="Stop" alt="Stop"><span><span>Stop</span></span></a>'+
			'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span class="good">'+version+'</span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'+
			'&nbsp;<a href="#" id="'+spocklet+'_close" class="sexy_button_new short red" title="Close" alt="Close"><span><span>Close</span></span></a>'+
		'</td></tr>'+
		'<tr><td colspan="3"><hr /></td></tr>'+
		'<tr><td colspan="3"><span id="'+spocklet+'_output"></span></td></tr>'+
		'<tr><td colspan="3"><span id="'+spocklet+'_input"><textarea id="'+spocklet+'_inputdata" cols=80 rows=20></textarea></span><br />'+
		'&nbsp;<a href="#" id="'+spocklet+'_start" class="sexy_button_new short green" title="Start"><span><span>Start</span></span></a>'+
		'&nbsp;<a href="#" id="'+spocklet+'_load" class="sexy_button_new short orange" title="Load from Post using Wizard-guide"><span><span>Load comments (wizard)</span></span></a>'+
		'&nbsp;<a href="#" id="'+spocklet+'_loadman" class="sexy_button_new short orange" title="Load from Post using permalink"><span><span>Load comments (manual)</span></span></a>'+
		'&nbsp;<a href="#" id="'+spocklet+'_post" class="sexy_button_new short red" title="Post to document"><span><span>Post results to document</span></span></a>'+
		'</td></tr>'+
		'<tr><td colspan="3"><hr /></td></tr>'+
		'<tr><td colspan="3">Showing <input id="'+spocklet+'_loglines" type="number" value="20" style="width:50px;" /> lines of log:<br /><span id="'+spocklet+'_log"></span></td></tr>'+
		'</table>'+
	'</div>';

	
	function unix_timestamp() {
		return parseInt(new Date().getTime().toString().substring(0, 10));
	}
	function cmp(v1,v2){
		return (v1>v2?-1:(v1<v2?1:0));
	}
	function create_div() {
		//setup the spockdiv
		if ($('#'+spocklet+'_main').length == 0) {
			$('#inner_page').before(spocklet_html);
		}
		else {
			//$('#'+spocklet+'_log').html();
		}
	}
	create_div();
	create_handler();

	/****** real action starts here *****/
	var stats={ opened:0,failed:0,total:0,msgs:{},sum:0 };
	var links=[];
	var run=false;

	function create_handler(){
		$('#'+spocklet+'_start').click(function(){
			run=true;
			load_links();
			return false;
		});
		$('#'+spocklet+'_stop').click(function(){
			run = false;
			return false;
		});
		$('#'+spocklet+'_load').click(function(){
			load_from_comments();
			return false;
		});
		$('#'+spocklet+'_loadman').click(function(){
			docid = /permalink\/(\d+)/.exec(prompt('Enter the full permalink (right-click timestamp).'))[1];
			load_comments(docid);
			return false;
		});
		$('#'+spocklet+'_close').click(function() {
			run = false;
			$('#'+spocklet+'_main').remove();
		});
		$e('post').click(function(){
			post_results();
			return false;
		});
	}
	
	function load_links(){
		var m,linkstext=$('#'+spocklet+'_inputdata').val();
		var lines=linkstext.split(/[\n]/);
		for(var i=0;i<lines.length;i++){
			if(m=/(https?\:\/\/[^\s]*)/.exec(lines[i])) {
				links.push(m[1]);
			}
		}
		$('#'+spocklet+'_inputdata').val(links.join("\n"));
		log("processing "+links.length+' links...');
		stats.sum=links.length;
		process_links();
	}
	function giftresult(msg) {
		try {
			var data=JSON.parse(msg);
			if(data.is_success) {
				return data.success_message
			}
		} catch(sowhat) {}
		return '';
	}	
	
	function process_links(){
		if((links.length>0)&&run){
			var link=links.shift();
			$('#'+spocklet+'_inputdata').val(links.join("\n"));
			
			//log("processing "+link);
			unshort(link,function(longurl){
				if(/^https?:\/\/.*facebook/.test(longurl)) {
					request_fburl(longurl,function(response){
						var $page = $('<div>'+response+'</div>');   
						var result = $page.find('.message_body:first').text()+''+$page.find('.fl_Msg').text()+''+$page.find('.fl_Sorry1').text()+$page.find('#asn_social_job_classic_jobs p').eq(1).text().trim();
						if(!result) {
							result=giftresult(response);
						}

//						var result = $(response).find('.message_body:first').text();
						log(result);
						stats.opened++; stats.total++;
						if(stats.msgs[result]) {
							stats.msgs[result]++;
						} else {
							stats.msgs[result]=1;
						}

						output();
						process_links();
					},function(){
						log("Error loading link, trying next link");
						process_links();
						stats.failed++; stats.total++;
					});
				} else {
					log("not a correct url: "+longurl.substr(0,20)+"..., skipping");
					stats.failed++; stats.total++;
					output();
					process_links();
				}
			});
		
		
		} else {
			log("all links processed");
			if(docid) {
				$e('post').css('display','inline-block');
			}
		}
	}
	
	function output(){
		html='';
		html+='Links processed: <span class="good">'+stats.total+'</span> of <span class="good">'+stats.sum+'</span><br />';
		html+='Links failed: <span class="bad">'+stats.failed+'</span><br />';
		html+='Links opened: <span class="good">'+stats.opened+'</span><br />';
		html+='<u>Link results: </u><br />';
		for(var msg in stats.msgs) {
			html+=msg + ' &times;  <span class="good">'+stats.msgs[msg]+'</span><br />';
		}
		$('#'+spocklet+'_output').html(html);
	}

	function unshort(url,handler) {
		try {
			var m;
			if(m=/(http\:\/\/[^\s]*)/.exec(url)) {
				url=m[1];
			}
		} catch(e){}
		//log('Trying url '+url);
		if(url.indexOf('spockon.me')!=-1) {
			if(alternative){
				log('Skipping Spockon.me link due to downtime');
				process_links();
			}
			else{
				//log('unspockon.me');
				$.ajax({
					type: "GET",
					dataType: "jsonp",
					url: '//spockon.me/api.php?action=expand&format=jsonp&shorturl='+escape(url),
					crossDomain: true,
					success: function (msg){
						var longurl = msg.longurl;
						handler(longurl);
						// TODO: add errorhandler
					}
				});
			}
		} else if(/(tinyurl|bit.ly|is.gd|goog.le|screepts.com|on.fb.me)/.test(url)) {
			//log('unshorten');
			$.getJSON('http://api.longurl.org/v2/expand?url='+escape(url)+'&format=json&callback=?',
			//$.getJSON('http://api.unshort.me/?r='+escape(url)+'&t=jsonp&callback=?',
			//$.getJSON('http://untiny.me/api/1.0/extract?url='+escape(url)+'&format=json&callback=?',
			//$.getJSON('http://expandurl.appspot.com/expand?url='+escape(url),
			//$.getJSON('http://www.unshorten.net/api.php?r='+escape(url)+'&t=jsonp&callback=?',
			//$.getJSON('http://therealurl.appspot.com?format=json&url='+escape(url)+'&callback=?',
				function (data) {
					var longurl = unescape(data['long-url']); //longurl.org
					//var longurl = unescape(data['resolvedURL']); //unshort.me
					//var longurl = unescape(data['org_url']); //untiny.me
					//var longurl = unescape(data['end_url']); //expandurl.appspot.com
					//var longurl = unescape(data['resolvedURL']); //unshorten.net
					//var longurl = unescape(data['url']); //therealurl.appspot.com
					//console.log(longurl);
					handler(longurl);
				}
			);		
		} else {
			handler(url);
		}
		
	}
	
	function post_results(){
		var text='Spockholm Linkopener reports:\n\n';
		text+='Links processed: '+stats.total+'\n';
		text+='Links failed: '+stats.failed+'\n';
		text+='Links opened: '+stats.opened+'\n';
		for(var msg in stats.msgs) {
			text+=msg + ' x '+stats.msgs[msg]+'';
		}
		text+='\n\nSpock on!';
		FB.api('/'+docid+'/comments','POST',{'message':text},function(result) {
			if(result.id) {
				log('Sucessfully posted, <a target="_blank" href="http://www.facebook.com/'+docid+'/?comment_id='+result.id+'">Click</a> to open.');
			} else {
				log('Error? '+JSON.stringify(result));
			}
			$e('post').css('display','none');
		});
	}

	function load_from_comments(){
		var html='';
		html+='<div '+$i('create_dialog')+'>';
	
		html+='<b>Load from a group doc/post</b><br />';
		
		html+='Step 1: Checking permissions<br />';
		html+='<span id="'+spocklet+'_permissions"></span><br />';
		
		html+='Step 2: Select the group<br />';
		html+='<span id="'+spocklet+'_groups"><span class="more_in">Groups loading... please wait!</span></span><br />';
		
		html+='Step 3: Select the document/post<br />';
		html+='<span id="'+spocklet+'_docs">Please select group first.</span><br />';

		html+='Step 4: Your settings<br />';
		html+='Fetch <input type="number" '+$i('hours')+' value="8" /> hours of comments<br />';
		
		html+='<br /><br />Now select "Load"!';
	
		html+='</div>';
		$e('create_dialog').remove();
		$('#popup_fodder').append(html);
		$e('create_dialog').dialog({
			title: version,
			minWidth: 550,
			modal: true,
			buttons: {
				'Load comments': function() {
					load_comments();
				},
				Cancel: function() {
					$e('create_dialog').remove();
				}
			}
		});				
		// permissions
		check_permission();	
	}
	function load_comments(docid){
		var since = unix_timestamp()-3600*parseInt($e('hours').val());
		if (!docid) {
			docid = $e('selectdoc').val();
		}
		if(isNaN(since)) { 
			since = parseInt(unix_timestamp()-3600*8);
		} 
		if(!docid) { return; }
		// FB.api(
			// {method:'fql.multiquery',queries:{
				// 'query1':'SELECT id,fromid,text,time,likes,user_likes FROM comment WHERE ((object_id="'+docid+'") OR (post_id="'+docid+'")) AND time>'+since+' ORDER BY time'
			// }},function(data){
				// var text='',i,data1=data[0].fql_result_set;
				// for(var i=0;i<data1.length;i++) {
					// var c=data1[i];
					// text+=c.text+'\n\n';
				// }
				// $e('inputdata').val(text);
				// $e('create_dialog').remove();
			// }
		// );
		FB.api('/'+docid+'/comments?limit=200',function(data){
			var str="";
			for(var i=0;i<data.data.length;i++) {
				var c=data.data[i];
				str+=' '+c.message;
			}
			var lines=str.split(/[\n]/);
			var links = [];
			lines=lines.reverse();
			
			for(var i=0;i<lines.length;i++){
				if(m=/(https?\:\/\/[^\s]*)/.exec(lines[i])) {
					links.push(m[1]);
				}
			}
			$e('inputdata').val(links.join("\n"));
			$e('create_dialog').remove();
		});
	}
	
	function load_groups(){
		// load groups
		FB.api('/me/groups?access_token=' +access_token+'', function(response) {
			var groupid=$g('group');

			if (Util.isset(response.error)) {
				$('#'+spocklet+'_groups').html('<span class="bad">Failed to load groups!</span><br />'+response.error.type+': '+response.error.message);
			}
			else {
				var output = '<select id="'+spocklet+'_selectgroup" style="width:100%;"><option value="">Select group</option>';
				for (var x=0;x<response.data.length;x++) {
					output += '<option value="'+response.data[x].id+'" '+(response.data[x].id==groupid?'selected':'')+'>'+response.data[x].name.substr(0,50)+'</option>';
				}
				output += '</select>';
				$e('groups').html(output);
				$e('selectgroup').change(function(){
					load_docs($(this).val());
					$s('group',$(this).val());
				});
				if(groupid) {
					load_docs(groupid);
				}
			}
		});
	}
	function load_docs(groupid) {
		FB.api('/'+groupid+'/feed',function(result){
			docid=$g('doc');
			//console.log(result);
			var html='<select '+$i('selectdoc')+'><option value="">Select document</option>';
			for(var i=0;i<result.data.length;i++){
					var title=result.data[i].subject || result.data[i].message || result.data[i].caption || "(no title)";
					html += '<option value="'+result.data[i].id+'" '+(result.data[i].id==docid?'selected':'')+'>'+title.substr(0,50)+'</option>';
			}
			html+='</select>';
			$e('docs').html(html);
			FB.api('/'+groupid+'/docs',function(result){
				for(var i=0;i<result.data.length;i++){
					$e('selectdoc').append('<option value="'+result.data[i].id+'">Document: '+result.data[i].subject+'</option>');
				}
			});
			$e('selectdoc').change(function(){
				$s('doc',$(this).val());
				docid=$(this).val();
			});
		});
	
	}	
	function check_permission(){
		FB.api('/me/permissions',function(result){
			if (Util.isset(result.data[0]) && Util.isset(result.data[0].user_groups) && Util.isset(result.data[0].publish_stream)) {
				$e('permissions').html('<span class="good">Permissions ok!</span>');
				load_groups();
			} else {
				$e('permissions').html('<span class="bad">No group permission. <a href="#" '+$i('reqperm')+'> Click here to request permission</a></span>');
				$e('reqperm').click(function(){
					FB.login(function (response) {setTimeout(check_permission,300);},{ "scope": "user_groups,publish_stream" });
					return false;
				});
			}
		});
	}
	
//"$(this).hide(); var feed = { picture:'https://zyngapv.hs.llnwd.net/e6/mwfb/graphics/LimitedTimeProperty/CageFightingArena/feed-up_90x90-CageFightArena.png', source:'', link:'http://apps.facebook.com/inthemafia/track.php?next_controller=limitedTimeProperty&next_action=upgradeBragFeed&zy_track=feed&from=p|95497006&sendkey=29b1ee6ce396caa943a5c1879cb147e7$$cdI(VWPY13bNY5*Uv_O*SL-r*tOXIJRVZHhM5l8THuF_v47NXpa8vSorfMXH3t-ixb(QDUsCTCiU5VlJUTyz5eVQZOISzlZ(XSPaI1IHE7hv98jSaj-&next_params=%7B%22target_id%22%3A%22p%7C95497006%22%2C+%22prop_id%22%3A%2221%22%2C+%22tid%22%3A%221330249859%22%2C+%22remote_key%22%3A%22d8765e3ef361d2911ea3be9fb145995a96d4a69303262ebb0aa3ede72c47ec16%22%7D&sendtime=1330249860&friend=p|95497006', name:'Check out my upgraded Cage Fight Arena', caption:' ', description:'I just upgraded my Cage Fight Arena to level 9. Check it out for a chance to earn a free item.', userMessage:'', actionLinks:[{'name': 'Get Parts', 'link': 'http://apps.facebook.com/inthemafia/track.php?next_controller=limitedTimeProperty&next_action=upgradeBragFeed&zy_track=feed&from=p|95497006&sendkey=29b1ee6ce396caa943a5c1879cb147e7$$cdI(VWPY13bNY5*Uv_O*SL-r*tOXIJRVZHhM5l8THuF_v47NXpa8vSorfMXH3t-ixb(QDUsCTCiU5VlJUTyz5eVQZOISzlZ(XSPaI1IHE7hv98jSaj-&next_params=%7B%22target_id%22%3A%22p%7C95497006%22%2C+%22prop_id%22%3A%2221%22%2C+%22tid%22%3A%221330249859%22%2C+%22remote_key%22%3A%22d8765e3ef361d2911ea3be9fb145995a96d4a69303262ebb0aa3ede72c47ec16%22%7D&sendtime=1330249860&friend=p|95497006'}], attachment:null, targetId:0, callback:function(resp) { post_id = null; if (resp != null) { if (Util.isset(resp.post_id)) { post_id = resp.post_id; } else if (Util.isset(resp.id)) { post_id = resp.id; } } if(post_id) { $('#property_upgrade_share_btn').show(); upgradePostedFeed('remote/html_server.php?xw_controller=LimitedTimeProperty&xw_action=postedUpgradePropertyFeed&xw_city=1&tmp=ed735a44eb2f110fa334965c173891f0&cb=631364a0605f11e193a0dd6739cae22a&xw_person=95497006&mwcom=1&target_id=p%7C95497006&tid=1330249859&part_id=&prop_id=21&prop_level=9&key=d8765e3ef361d2911ea3be9fb145995a96d4a69303262ebb0aa3ede72c47ec16'); trackFBFeedSend('29b1ee6ce396caa943a5c1879cb147e7$$cdI(VWPY13bNY5*Uv_O*SL-r*tOXIJRVZHhM5l8THuF_v47NXpa8vSorfMXH3t-ixb(QDUsCTCiU5VlJUTyz5eVQZOISzlZ(XSPaI1IHE7hv98jSaj-', 1130821645, 1330249860, post_id); } else { upgradePostFailed(); } }, autoPublish:true, ref:'limited_time_p' }; MW.Feed(feed);"

	function request_fburl(url, handler, errorhandler) {
		url = url.replace('http://apps.facebook.com/inthemafia/track.php?','');
		url = url.replace('https://apps.facebook.com/inthemafia/track.php?','');
		url = url.replace(/next_/g,'xw_');
		var strparams = '';
		if (params = /params=(\{.*\})/.exec(url)) {
			try {
				params = jQuery.parseJSON(params[1].replace(/[\+\%]/g,''));
			}
			catch (parseproblem) {
				//console.log(parseproblem+' '+unescape(params[1]).replace(/[\+\%]/g,''));
			}
			for (x in params) {
				strparams += '&'+x+'='+params[x];
			}
			url = url.substr(0,url.indexOf('&xw_params'));
		}
		if (params = /params=(%7B.*%7D)/.exec(url)) {
			try {
				params = jQuery.parseJSON(unescape(params[1]).replace(/[\+\%]/g,''));
			}
			catch (parseproblem) {
				//console.log(parseproblem+' '+unescape(params[1]).replace(/[\+\%]/g,''));
			}
			for (x in params) {
				strparams += '&'+x+'='+params[x];
			}
			url = url.substr(0,url.indexOf('&xw_params'));
		}
		url = url+strparams;
		url=url.replace('http://facebook-ca2.mafiawars.zynga.com/mwfb/remote/html_server.php?','');
		url=url.replace('https://facebook-ca2.mafiawars.zynga.com/mwfb/remote/html_server.php?','');
		console.log(url);
		var timestamp = parseInt(new Date().getTime().toString().substring(0, 10));
		if (url.indexOf('cb=') == -1) {
			url += '&cb='+User.id+timestamp;
		}
		if (url.indexOf('tmp=') == -1) {
			url += '&tmp='+timestamp;
		}
		User.clicks++;
		var params = {
			'ajax': 1,
			'liteload': 1,
			'sf_xw_user_id': User.id,
			'sf_xw_sig': local_xw_sig,
			'xw_client_id': 8,
			'skip_req_frame': 1,
			'clicks': User.clicks
		};
		$.ajax({
			type: "POST",
			url: preurl+url,
			data: params,
			cache: false,
			success: handler,
			error: errorhandler
		});
	}
	
	
	
	function request(url, handler, errorhandler) {
		var timestamp = parseInt(new Date().getTime().toString().substring(0, 10));
		if (url.indexOf('cb=') == -1) {
			url += '&cb='+User.id+timestamp;
		}
		if (url.indexOf('tmp=') == -1) {
			url += '&tmp='+timestamp;
		}
		User.clicks++;
		var params = {
			'ajax': 1,
			'liteload': 1,
			'sf_xw_user_id': User.id,
			'sf_xw_sig': local_xw_sig,
			'xw_client_id': 8,
			'skip_req_frame': 1,
			'clicks': User.clicks
		};
		$.ajax({
			type: "POST",
			url: preurl+url,
			data: params,
			cache: false,
			success: handler,
			error: errorhandler
		});
	}	

	function $e(element,more) {
		return $('#'+spocklet+'_'+element+(more?' '+more:''));
	}
	function $ec(element,more) {
		return $('.'+spocklet+'_'+element+(more?' '+more:''));
	}
	function $i(element) {
		return 'id="'+spocklet+'_'+element+'"';
	}
	function $c(element,spockclasses,otherclasses) {
		var i,str=' class="'+spocklet+'_'+element+'';
		if($.isArray(spockclasses)) {
			for(i=0;i<spockclasses.length;i++) {
				str+=' '+spocklet+'_'+spockclasses[i];
			}
		}
		if($.isArray(otherclasses)) {
			for(i=0;i<otherclasses.length;i++) {
				str+=' '+otherclasses;
			}
		}
		str+='"';
		return str;
	}
	function $s(name,value) {
		storage.setItem(spocklet+'_'+name+'_'+User.trackId, value);
	}
	function $g(name) {
		return storage.getItem(spocklet+'_'+name+'_'+User.trackId);
	}
	function $b(name,text,color,mouseover) {
		if(!color) { color="black"; }
		if(!mouseover) { mouseover = text; }
		return '<a href="#" id="'+spocklet+'_'+name+'" class="sexy_button_new short '+color+'" title="'+mouseover+'"><span><span>'+text+'</span></span></a>';
	}
	// by Eike
	String.prototype.re = function(regex){
		var r=new RegExp(regex);
		var m;
		if(m=r.exec(this)) {
			return m[1];
		} else {
			return '';
		}
	}	
	function min(a,b){
		return a<b?a:b;
	}
	function max(a,b){
		return a>b?a:b;
	}
	function imgurl(img,w,h,a) {
		return '<img src="http://mwfb.static.zgncdn.com/mwfb/graphics/'+img+'" width="'+w+'" height="'+h+'" title="'+a+'" alt="'+a+'" align="absmiddle">';
	}
	function commas(s) {
		while (d=/(-)?(\d+)(\d{3}.*)/.exec(s)) {
			s = (d[1]?d[1]+d[2]+','+d[3]:d[2]+','+d[3]);
		}
		return s;
	}
	function timestamp() {
		now = new Date();
		var CurH = now.getHours();
		CurH = (CurH<10?'0'+CurH:CurH);
		var CurM = now.getMinutes();
		CurM = (CurM<10?'0'+CurM:CurM);
		var CurS = now.getSeconds();
		CurS = (CurS<10?'0'+CurS:CurS);
		return '<span class="more_in">['+CurH+':'+CurM+']</span> ';
	}	

	function log(message){
		message='<span class="more_in">'+timestamp()+'</span> '+message;
		var limit = parseInt($('#'+spocklet+'_loglines').val());
		logs.unshift(message);
		if (limit > 0) {
			if (logs.length>limit) {
				message=logs.pop();
			}
		}
		$('#'+spocklet+'_log').html(logs.join('<br />'));
	}	
	

	//add analytics
	function loadContent(file){
		var head = document.getElementsByTagName('head').item(0);
		var scriptTag = document.getElementById('loadScript');
		if(scriptTag) head.removeChild(scriptTag);
			script = document.createElement('script');
			script.src = file;
			script.type = 'text/javascript';
			script.id = 'loadScript';
			head.appendChild(script);
	}
	loadContent('https://www.google-analytics.com/ga.js');
	try {
		var pageTracker = _gat._getTracker("UA-8435065-3");
		pageTracker._trackPageview();
		pageTracker._trackPageview("/script/"+spocklet);
	}
	catch(err) {}
	//end analytics
})()
